package com.bayihouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.constant.CommonConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.mapper.UnitMapper;
import com.bayihouse.model.entity.Unit;
import com.bayihouse.model.request.unit.UnitQueryRequest;
import com.bayihouse.model.vo.UnitVO;
import com.bayihouse.service.UnitService;
import com.bayihouse.utils.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【unit】的数据库操作Service实现
 * @createDate 2024-09-17 10:28:03
 */
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit>
        implements UnitService {

    @Override
    public UnitVO getUnitVO(Unit unit) {
        if (unit == null) {
            return null;
        }
        return UnitVO.objToVO(unit);
    }

    @Override
    public QueryWrapper<Unit> getQueryWrapper(UnitQueryRequest unitQueryRequest) {
        if (unitQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = unitQueryRequest.getId();
        String name = unitQueryRequest.getName();
        Long houseId = unitQueryRequest.getHouseId();
        String sortField = unitQueryRequest.getSortField();
        String sortOrder = unitQueryRequest.getSortOrder();
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
       queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(houseId != null, "father_id", houseId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public List<UnitVO> getUnitVOList(List<Unit> records) {
        if (CollectionUtils.isEmpty(records)) {
            return new ArrayList<>();
        }
        return records.stream().map(this::getUnitVO).collect(Collectors.toList());
    }

    @Override
    public Long getUnitByHouseIdAndAddress(Long houseId, String address) {
        if (houseId == null || StringUtils.isBlank(address)) {
            return null;
        }
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("houseId", houseId);
        queryWrapper.like("address", address);
        return this.getOne(queryWrapper).getId();
    }
}




